//
//  MyFavoriteViewController.m
//  MyTravel
//
//  Created by Hunk on 11-5-27.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "MyFavoriteViewController.h"
#import "AsyncLoadingImageView.h"
#import "JourneyMenuViewController.h"
#import "NetworkManager.h"

#define TAG_ACTIVITYINDICATORVIEW 13
#define TAG_TABLEVIEW 15

@interface MyFavoriteViewController (Private)

-(void)addLabelOnCell:(UITableViewCell*)cell 
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode
		textAlignment:(UITextAlignment)textAlignment;

@end

@implementation MyFavoriteViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewWillAppear:(BOOL)animated
{
    m_nCurrentPageNumber = 1;
    NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSString stringWithFormat:@"%d", m_nCurrentPageNumber], @"page_number", 
                                [NSString stringWithFormat:@"%d", PAGE_SIZE_JOURNEY], @"page_size", nil];
    
    [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_GetMyFavoriteJourney
                                                   WithParameters:parameters
                                                 AndCallBackScope:self
                                                    AndSuccessSel:@"onSuccess:"
                                                     AndFailedSel:@"onFailed:"];
}

#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    arrayMyFavoriteNews = [[NSMutableArray alloc] init];
    
    // Right edit bar button
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleBordered target:self action:@selector(rightBarButtonItemHandle:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    [rightBarButtonItem release];
    
    // Init tableView
	UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 367) 
                                                          style:UITableViewStylePlain];
    [tableView setBackgroundColor:[UIColor clearColor]];
    tableView.delegate = self;
	tableView.dataSource = self;
    tableView.tag = TAG_TABLEVIEW;
	[self.view addSubview:tableView];
    [tableView release];
}

#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return [arrayMyFavoriteNews count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{	
	return 80.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
	static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier:CellIdentifier] autorelease];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    
    // Cell Background view
    UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    [bgImageView setImage:[UIImage imageNamed:@"CellBackground.png"]];
    [cellBgView addSubview:bgImageView];
    [bgImageView release];
    [cell setBackgroundView:cellBgView];
    [cellBgView release];
    
    // Get one news
    NSDictionary* newsDictionary = [arrayMyFavoriteNews objectAtIndex:indexPath.row];
    
    // Load and add imageView
    AsyncLoadingImageView* asyncLoadingImageView = [[[AsyncLoadingImageView alloc] initWithFrame:CGRectMake(10, 10, 90, 60)] autorelease];
    [asyncLoadingImageView loadImageFromURLString:[newsDictionary objectForKey:KEY_IMAGE] 
                                 placeholderImage:nil];
    [cell.contentView addSubview:asyncLoadingImageView];
    
    // Title
    [self addLabelOnCell:cell 
                    text:[newsDictionary objectForKey:KEY_TITLE] 
                   frame:CGRectMake(110, 0, 200, 30) 
                 bgColor:[UIColor clearColor] 
               textColor:[UIColor blackColor] 
              fontOfSize:[UIFont systemFontOfSize:16] 
           lineBreakMode:UILineBreakModeTailTruncation 
           textAlignment:UITextAlignmentLeft];
    
    // Time
    [self addLabelOnCell:cell 
                    text:[NSString stringWithFormat:@"出发日期：%@", [newsDictionary objectForKey:KEY_STARTINGTIME]] 
                   frame:CGRectMake(110, 32, 170, 20) 
                 bgColor:[UIColor clearColor] 
               textColor:[UIColor grayColor] 
              fontOfSize:[UIFont italicSystemFontOfSize:14] 
           lineBreakMode:UILineBreakModeTailTruncation 
           textAlignment:UITextAlignmentLeft];
    
    // Address
    [self addLabelOnCell:cell 
                    text:[NSString stringWithFormat:@"出发地点：%@", [newsDictionary objectForKey:KEY_STARTINGADDRESS]] 
                   frame:CGRectMake(110, 55, 100, 20) 
                 bgColor:[UIColor clearColor] 
               textColor:[UIColor blackColor] 
              fontOfSize:[UIFont italicSystemFontOfSize:14] 
           lineBreakMode:UILineBreakModeTailTruncation 
           textAlignment:UITextAlignmentLeft];
    
    // Price
    [self addLabelOnCell:cell 
                    text:[NSString stringWithFormat:@"￥%@", [newsDictionary objectForKey:KEY_PRICE]] 
                   frame:CGRectMake(220, 55, 80, 20) 
                 bgColor:[UIColor clearColor] 
               textColor:[UIColor magentaColor] 
              fontOfSize:[UIFont boldSystemFontOfSize:14] 
           lineBreakMode:UILineBreakModeTailTruncation 
           textAlignment:UITextAlignmentLeft];
    
    return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // Go to journeyMenuViewController
    JourneyMenuViewController* journeyMenuViewController = [JourneyMenuViewController alloc];
    journeyMenuViewController.hidesBottomBarWhenPushed = YES;
    journeyMenuViewController.titleForHeader = @"威尼斯";
    [self.navigationController pushViewController:journeyMenuViewController animated:YES];
    [journeyMenuViewController release];
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
//        // Delete the row from the data source.
//        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert)
    {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

#pragma mark -
#pragma mark moreButtonHandle
- (void)rightBarButtonItemHandle:(id)sender
{
    UIBarButtonItem* rightBarButtonItem = (UIBarButtonItem*)sender;
    if([rightBarButtonItem.title isEqualToString:@"编辑"])
    {
        [rightBarButtonItem setTitle:@"完成"];
        
        UITableView* tableView = (UITableView*)[self.view viewWithTag:TAG_TABLEVIEW];
        
        [tableView setEditing:YES animated:YES];
    }
    else
    {
        [rightBarButtonItem setTitle:@"编辑"];
        
        UITableView* tableView = (UITableView*)[self.view viewWithTag:TAG_TABLEVIEW];
        
        [tableView setEditing:NO animated:YES];
    }
}

#pragma mark -
#pragma mark Callback methods
- (void)onSuccess:(id)sender
{
    NSDictionary* resultDic = (NSDictionary*)sender;
    
    NSLog(@"resultDic = %@\n", resultDic);
}

- (void)onFailed:(id)sender
{}

#pragma mark -
#pragma mark addLabelOnCell
-(void)addLabelOnCell:(UITableViewCell*)cell
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode 
		textAlignment:(UITextAlignment)textAlignment
{
	if(!bgColor) bgColor = [UIColor grayColor];
	if(!textColor) textColor = [UIColor blackColor];
	if(!fontOfSize) fontOfSize = [UIFont systemFontOfSize:16];
	if(!text) text = [NSString stringWithString:@"请输入Label内容"];
	
	UILabel* titleLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
	titleLabel.backgroundColor = bgColor;
	titleLabel.textColor = textColor;
	titleLabel.font = fontOfSize;
	titleLabel.lineBreakMode = UILineBreakModeCharacterWrap;
	titleLabel.textAlignment = textAlignment;
	titleLabel.text = text;
	[cell.contentView addSubview:titleLabel];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
